import requests
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist

sys.path.append("..")
from src.vobjects.item import Item

from src.history import History

class Anilibria(Plugin):

    def __init__(self, history: History=History()):
        self.name = "AnilibriaTV: Search"
        self.is_query_required = True
        self.query_description = """"""
        self.history = history

        self.flag = "-als"
        self.full_flag = "--anilibriasearch"
        self.flag_help = "search anilibria titles"
        self.flag_action = ""

        self.api_instance = "https://api.anilibria.tv/v2"
        self.instance = "https://anilibria.tv"

    def get_search(self, query: str=""):
        resp = requests.get(f"{self.api_instance}/searchTitles", 
            {
                "search" : query
            }
        )

        if resp.status_code != 200: return list()
        resp = resp.json()

        items = []
        for it in resp:
            title = f"{it['names']['ru']} ({it['names']['en']})"
            host = "https://" + it["player"]["host"]
            purl = f"{self.instance}/release/{it['code']}.html"
            videos = list()

            for vid in it["player"]["playlist"].values():
                ititle = "Episode " + str(vid["serie"])
                video = PluginVideo(
                    title=ititle,
                    playlist_title=title,
                    url=host+vid["hls"]["hd"],
                    length=it["type"]["length"]
                )
                
                inHistory = video.in_history(self.history)
                item = video.to_item(inHistory=inHistory)
                item.fstr = f"{video.length} minutes"

                videos.append(item)

            playlist = PluginPlaylist(title, videos, url=purl)

            item = playlist.to_item()

            items.append(item)

        return items

    def get_items_by_query(self, query: str=""):
        return self.get_search(query=query)

    def get_items(self):
        return list()

if __name__ == "__main__":
    al = Anilibria()

    items = al.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




